
<template>
  <div style="display: inline-block">
    <span>{{ dictValue }}</span>
  </div>
</template>
<script>
import { selectByDictKey } from '@/api/dict'
export default {
  name: 'DictValue',
  props: {
    dictKey: {
      type: String,
      default() {
        return ''
      }
    },
    value: {
      type: String,
      default() {
        return ''
      }
    }
  },
  data() {
    return {
      dictValue: '',
      dataList: []
    }
  },
  watch: {
    value: {
      immediate: true,
      async handler() {
        await this.initDictData()
      }
    },
    dictKey: {
      immediate: true,
      async handler() {
        await this.initDictData()
      }
    }
  },
  methods: {
    initDictData() { // 获取对应字典数据
      const item = sessionStorage.getItem(this.dictKey)
      if (!item || item.length === 0 || item === '[]') {
        selectByDictKey(this.dictKey).then(resp => {
          if (resp.success) {
            this.init(resp.data)
            sessionStorage.setItem(this.dictKey, JSON.stringify(resp.data))
          }
        })
      } else {
        this.init(JSON.parse(item))
      }
    },
    init(dictOptions) {
      const value = this.value
      if (dictOptions) {
        const result = dictOptions.filter(e => {
          return String(e.itemKey) === String(value)
        })
        if (result && result.length > 0) {
          this.dictValue = result[0].itemName
        } else {
          this.dictValue = '-'
        }
      } else {
        this.dictValue = '-'
      }
    }
  }
}
</script>

<style scoped>
.loading {
  position: fixed;
  z-index: 9999;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
